//
//  YBStorydetialViewController.m
//  OurTourism
//
//  Created by dllo on 15/11/26.
//  Copyright © 2015年 Devil_Coming. All rights reserved.
//

#import "YBStorydetialViewController.h"
#import "YBstorydetialTableViewCell.h"
#import "Header.h"
#import "YbManagementData.h"
BOOL have ;  // 用于反馈 判断结果
@interface YBStorydetialViewController ()<UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, retain)UITableView *tableView;
@property (nonatomic, retain)NSMutableArray *modelDetailArr;
@property (nonatomic, retain)NSMutableDictionary *userDic;
@property (nonatomic, retain)NSMutableDictionary *detailDic;     //获取当前页文章信息总数据
@property (nonatomic, assign)CGFloat hTitleLable;  //记录第一个分区title的高度
@property (nonatomic, retain)YBDestinationModel *storyModel;
@property (nonatomic, strong)MBProgressHUD *hud;
@property (nonatomic, strong)YbManagementData *manage;
@property (nonatomic, strong)UIButton *likebtn;



@end

@implementation YBStorydetialViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 获取数据
    [self AcquireData];
    // 创建 btn 方法
    [self CreatBtn];
    
    
    
    
    
    self.view.backgroundColor = [UIColor colorWithRed:0.98 green:0.97 blue:0.93 alpha:1];
    //    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:nil]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(backToLast)];
    self.navigationController.navigationBar.translucent = NO;
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    self.title = @"故事详情";
    
    
    // Do any additional setup after loading the view.
    [self getData];
    //创建tableView
    [self createTableView];
    [self loadMBProgress];
    
    [self CreatBtn];
    
    
    
}



// 获取数据
- (void)AcquireData
{
    
    NSString *str = [NSString stringWithFormat:@"%@",self.spot_id];
    
    // 打开数据库
    self.manage = [YbManagementData shareInstance];
    [self.manage openDB];
    // 创建临时数组用于保存数据库获取数据
    NSMutableArray *TemporaryArr = [self.manage selectFromTable];
    
    if (!TemporaryArr) {
        TemporaryArr = [NSMutableArray array];
    }
    else{
        for (YBDestinationModel *temp in TemporaryArr) {
            if ([temp.collect isEqualToString:str]) {
                have = YES;      //判断此页面 access_url 与数据库中是够有相同的   返回(YES)
            }
        }
    }
}
- (void) CreatBtn  // 按钮创建
{
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(20, 20, 40, 40);
    [btn setImage:[UIImage imageNamed:@"iconfont-iconfonticonfontjiantouzuo11@2x"] forState:0];
    [btn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
    
    self.likebtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.likebtn.frame = CGRectMake(120, 20, 40, 40);
    
    [self.likebtn addTarget:self action:@selector(liketo) forControlEvents:UIControlEventTouchUpInside];
    self.likebtn.backgroundColor = [UIColor yellowColor];
    // LikeBtn 图片 判断
    if(have){
        //Likebtn 跟换图片   视图明确  (标记)
        self.likebtn.backgroundColor = [UIColor redColor];
        // [self.LikeBtn setImage:[UIImage imageNamed:@"islike"] forState:UIControlStateNormal];
    }else
    {
        self.likebtn.backgroundColor = [UIColor yellowColor];
        // [self.LikeBtn setImage:[UIImage imageNamed:@"like"] forState:UIControlStateNormal];
    }
    
    
    [self.view addSubview:self.likebtn];
    
}

- (void)liketo
{
    [self.manage creatTable]; // 创建数据库表
    
    NSString *str = [NSString stringWithFormat:@"%@",self.spot_id];
    if (have) {
        [self.manage deleteWithTopic_name:str];// 删除  传入值为对象
        // [self.LikeBtn setImage:[UIImage imageNamed:@"like"] forState:UIControlStateNormal];//点击时进行图片更换
        self.likebtn.backgroundColor = [UIColor redColor];
        have = NO;
    }
    else {
        self.likebtn.backgroundColor = [UIColor yellowColor];
        YBDestinationModel *tem = [YBDestinationModel alloc];
        tem.collect = str;
        tem.index_cover = self.recommendModel.index_cover;
        tem.index_title = self.recommendModel.index_title;
        
        
        
        [self.manage insertWithStudent:tem];  //添加 传入值为对象
        
        
        //        [self.LikeBtn setImage:[UIImage imageNamed:@"islike"] forState:UIControlStateNormal];//点击时进行图片更换
        have = YES;
    }
    
}


- (void)back
{
    [self dismissViewControllerAnimated:YES completion:^{
    }];
}

- (void)loadMBProgress
{
    self.hud = [[MBProgressHUD alloc] initWithView:self.view];
    
    self.hud.dimBackground = NO;
    //设置对话框文字
    self.hud.labelText = @"loading";
    self.hud.minShowTime = 50;
    self.hud.activityIndicatorColor = [UIColor whiteColor];
    self.hud.labelColor = [UIColor whiteColor];
    
    [self.view addSubview:self.hud];
    [self.hud showAnimated:YES whileExecutingBlock:^{
        //对话框显示时需要执行的操作
        sleep(1);
    } completionBlock:^{
        //操作执行完后取消对话框
        [self.hud removeFromSuperview];
        self.hud = nil;
    }];
    
}




#pragma mark - 获取数据
- (void)getData
{
    NSString *url = [NSString stringWithFormat:@"%@%@", @"http://api.breadtrip.com/v2/new_trip/spot/?spot_id=",self.spot_id];
    [MZNetHandle getUrl:url cookie:nil result:^(id result) {
        //用来接收result
        NSMutableDictionary *dic = result;
        
        
        //获取当前页文章信息总数据
        self.detailDic = dic[@"data"][@"spot"];
        //获取当前页用户信息数据
        self.userDic = dic[@"data"][@"trip"][@"user"];
        
        //将文章信息数据转化为对象
        self.modelDetailArr = [YBDestinationModel transformWithArray:self.detailDic[@"detail_list"]];
        [self.hud removeFromSuperview];
        [self.tableView reloadData];
        
    }];
}

#pragma mark - 创建tableView
- (void)createTableView
{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGTH - 80) style:UITableViewStyleGrouped];
    self.tableView.backgroundColor = [UIColor colorWithRed:0.98 green:0.97 blue:0.93 alpha:1];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle =    UITableViewCellSeparatorStyleNone;
    
    [self.view addSubview:self.tableView];
    
    
}



- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    //一个分区保存title 一个分区保存图和字的数据
    return 2;
}

#pragma mark - 头部行高
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return WIDTH / 3;
    }
    else{
        return 0;
    }
}

#pragma mark - header上面的view
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 100)];
        view.backgroundColor = [UIColor colorWithRed:0.98 green:0.97 blue:0.93 alpha:1];
        
        
        //头像
        UIImageView *img = [[UIImageView alloc]initWithFrame:CGRectMake(30, 30, WIDTH / 6, WIDTH / 6)];
        img.layer.masksToBounds = YES;
        img.layer.cornerRadius = img.frame.size.width / 2;
        [view addSubview:img];
        
        [img sd_setImageWithURL:[NSURL URLWithString:self.userDic[@"avatar_m"]]];
        
        //文字
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(img.frame.origin.x + img.frame.size.width + 10, img.frame.origin.y + 20, HEIGTH - 30- img.frame.size.height - 20 - 20, 30)];
        [view addSubview:label];
        label.font = [UIFont fontWithName:@" Menlo-Italic" size:15];
        label.text = self.userDic[@"name"];
        
        //横线label
        UILabel *labelLine = [[UILabel alloc]initWithFrame:CGRectMake(20, img.frame.origin.y + img.frame.size.height + 10, WIDTH - 60, 1)];
        labelLine.backgroundColor = [UIColor darkGrayColor];
        [view addSubview:labelLine];
        
        return view;
    }
    else
    {
        return nil;
    }
    
}

#pragma mark - footer的高度
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == 0) {
        return 0;
    }
    else
    {
        return WIDTH / 3 - 50;
    }
}

#pragma mark - tableViewfooterView
//时间view
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if (section == 0) {
        return nil;
    }
    else{
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, WIDTH / 3 - 50)];
        view.backgroundColor = [UIColor colorWithRed:0.98 green:0.97 blue:0.93 alpha:1];
        
        //横线label
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(30, 0, WIDTH - 60, 1)];
        label.backgroundColor = [UIColor darkGrayColor];
        [view addSubview:label];
        
        //时间图片
        UIImageView *img = [[UIImageView alloc]init];
        img.frame = CGRectMake(30, view.frame.size.height / 2 - 10, 20, 20);
        img.image = [UIImage imageNamed:@"time"];
        [view addSubview:img];
        
        
        //时间
        UILabel *lable = [[UILabel alloc]init];
        label.font = [UIFont systemFontOfSize:13];
        lable.frame = CGRectMake(img.frame.origin.x + 20 + 10, img.frame.origin.y, 300, img.frame.size.height);
        lable.textColor = [UIColor darkGrayColor];
        
        
        NSString *str = [self.detailDic[@"date_tour"]  substringToIndex:19];
        NSString *str1 = [str stringByReplacingOccurrencesOfString:@"T" withString:@"  "];
        lable.text = str1;
        
        [view addSubview:lable];
        
        
        
        return view;
    }
    
}

#pragma mark - tableViewc cell的count
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }
    else{
        return self.modelDetailArr.count;
        
    }
}
#pragma mark - tableView cell的数据
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.section == 0) {
        UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:@"cell"];
        if (!cell) {
            cell =   [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
            
        }
        cell.backgroundColor = [UIColor colorWithRed:0.98 green:0.97 blue:0.93 alpha:1];
        
        cell.textLabel.text = self.detailDic[@"text"];
        cell.textLabel.numberOfLines = 0;
        cell.textLabel.textColor = [UIColor darkGrayColor];
        cell.textLabel.font = [UIFont systemFontOfSize:17];
        self.hTitleLable = [[self class]heightWithText:cell.textLabel.text fontSize:17 Width:WIDTH - 40];
        return cell;
    }
    else
    {
        YBstorydetialTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"storyDetail"];
        if (!cell) {
            cell = [[YBstorydetialTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"storyDetail"];
        }
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        cell.backgroundColor = [UIColor colorWithRed:0.98 green:0.97 blue:0.93 alpha:1];
        cell.detailModel = self.modelDetailArr[indexPath.row ];
        cell.userDic = self.userDic;
        return cell;
    }
}


#pragma mark - tableView行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //0分区 返回文章标题
    if (indexPath.section == 0) {
        return self.hTitleLable ;
    }
    else{
        
        YBDestinationModel *tempModel = self.modelDetailArr[indexPath.row];
        CGFloat h = [[self class]heightWithText:tempModel.text fontSize:15 Width:WIDTH - 40];
        return (tempModel.photo_height).integerValue * WIDTH / (tempModel.photo_width).integerValue + h + 50;
        
    }
}

//计算文本高度的方法
+ (CGFloat)heightWithText:(NSString *)text fontSize:(CGFloat)fontsize Width:(CGFloat)width

{
    //设置一个字典 保存文本属性
    NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:fontsize]};
    
    //预设尺寸 文本最大不会超过这个范围
    CGSize size = CGSizeMake(width, 2000);
    //根据文本信息 计算得到一个CGRect
    //参数1. 尺寸范围
    //参数2. 获取文本尺寸的方式
    //参数3. 文本属性
    //参数4. 无用信息(上下文)
    CGRect rect = [text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    return rect.size.height;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
